﻿//methods: GenerateKey,EnscryptFile,DescryptFile- source: http://support.microsoft.com/kb/307010
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Security.AccessControl;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;

namespace Movement_Trajectory_Analysis
{
    public class MTAF
    {

        public static string[] lines;
        [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]//  Call this function to remove the key from memory after use for security.
        public static extern bool ZeroMemory(ref string Destination, int Length);

        static string GenerateKey() // Function to Generate a 64 bits Key.
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create(); // Create an instance of Symetric Algorithm. Key and IV is generated automatically.
            return ASCIIEncoding.ASCII.GetString(desCrypto.Key); // Use the Automatically generated key for Encryption. 
        }

        static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
        {
            FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
            FileStream fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write);
            byte[] bytearrayinput = new byte[fsInput.Length];
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Close();
            fsInput.Close();
            fsEncrypted.Close();
        }

        public static void DecryptFile(string sKey, string @fname)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            //A 64 bit key and IV is required for this provider.
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //Set secret key For DES algorithm.
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);//Set initialization vector.
            string sInputFilename = @fname;
            string sOutputFilename = "descrypted.mta";


            FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read); //Create a file stream to read the encrypted file back.

            ICryptoTransform desdecrypt = DES.CreateDecryptor();//Create a DES decryptor from the DES instance.
            //Create crypto stream set to read and do a 
            CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);//DES decryption transform on incoming bytes.
            StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);//Print the contents of the decrypted file.
            fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
            fsDecrypted.Flush();
            fsDecrypted.Close();
            fsread.Close();
        }

        public static void SaveMTA(string @fName)//save results to file .mta
        {

            FileStream fs = new FileStream("encry.mta", FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write("MTA");
            sw.WriteLine();

            for (int j = 0; j < MTA.user_colors.Length; j++)
            {
                sw.WriteLine("Dla koloru: " + MTA.user_colors[j].R.ToString() + "," + MTA.user_colors[j].G.ToString() + "," + MTA.user_colors[j].B.ToString());
                for (int i = 0; i < MTA.frames.Length; i++)
                {
                    sw.Write("Punkt" + Convert.ToString(i + j * MTA.frames.Length) + "[" + MTA.trajectory[i + j * MTA.frames.Length, 0] + ",");
                    sw.Write(MTA.trajectory[i + j * MTA.frames.Length, 1] + "]");
                    sw.WriteLine();
                }
                sw.WriteLine();
            }
            sw.Close();
            EncryptFile("encry.mta", @fName, "12345678");
            File.Delete("encry.mta");
        }

        public static void OpenMTA()// open .mta to richBox1
        {

            OpenFileDialog ofmta = new OpenFileDialog();
            ofmta.Filter = "MTA file (*.mta)|*.mta";

            if (ofmta.ShowDialog() == DialogResult.OK)
            {
                DecryptFile("12345678", @ofmta.FileName);
            }
        }

        public static void SaveTXT() // convert from .mta to .txt
        {
            OpenFileDialog ofmta1 = new OpenFileDialog();
            ofmta1.Filter = "MTA file (*.mta)|*.mta";

            if (ofmta1.ShowDialog() == DialogResult.OK)
            {
                DecryptFile("12345678", @ofmta1.FileName);  
            }
            SaveFileDialog saveResults = new SaveFileDialog();
            saveResults.Filter = "txt files (*.txt)|*.txt";
            if (saveResults.ShowDialog() == DialogResult.OK)
            {
                StreamWriter sw = new StreamWriter(@saveResults.FileName);
                sw.Write(System.IO.File.ReadAllText("descrypted.mta"));
                sw.Close();
                File.Delete("descrypted.mta");
            }

        }
    }
}
